import { config } from "@/config";

let defalut_userInfo: any = {};

// 用户关闭了本地存储功能，此时在外层加个try...catch
try {
  if (Object.keys(defalut_userInfo).length == 0) {
    defalut_userInfo = JSON.parse(
      window.localStorage.getItem(config.system_prefix + "userInfo") as string
    );
  }
} catch (e) {
  console.error("浏览器本地存储异常");
}

const state = {
  userInfo: defalut_userInfo,
};

const mutations = {
  changeUserInfo(state: any, action: any) {
    state.userInfo = action.userInfo;
    try {
      // 数据改变的时候把数据拷贝一份保存到localStorage里面
      window.localStorage.setItem(
        config.system_prefix + "userInfo",
        JSON.stringify(state.userInfo)
      );
    } catch (e) {
      console.error("浏览器本地存储异常");
    }
  },
};

const actions = {
  CHANGEUSERINFO(dispatch: any, userInfo: any) {
    let action = {
      type: "changeUserInfo",
      userInfo,
    };
    dispatch.commit(action);
  },
  LOGIN_OUT(dispatch: any) {
    localStorage.removeItem(config.system_prefix + "userInfo");
  },
};

const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
